/*
 * Copyright (C) 2006 Jeffrey Palm.  All rights reserved. 
 */

import java.awt.*;
import java.util.*;
import java.util.List;
import javax.swing.*;

public class LoginInfoFrame {
  
  private String username;
  private String password;
  private boolean isChecked;
  private boolean isCancelled;

  private final JTextField usernameField;
  private final JTextField passwordField;
  private final JPanel mainPanel;
  private final JCheckBox check;
  
  public String getUsername()  {return username;}
  public String getPassword()  {return password;}
  public boolean isChecked()   {return isChecked;}
  public boolean isCancelled() {return isCancelled;}

  public void setUsername(String username) {usernameField.setText(this.username = username);}
  public void setPassword(String password) {passwordField.setText(this.password = password);}

  void addAdditionalButton(AbstractAction b) {
    JPanel row = newPanel();
    row.add(new JButton(b));
    mainPanel.add(row);    
  }
  
  private JPanel newPanel() {
    JPanel p = new JPanel();
    p.setLayout(new FlowLayout(FlowLayout.LEFT));
    return p;
  }
    
  public LoginInfoFrame(String username, String password) {
    this.username = username;
    this.password = password;

    JPanel p = newPanel();
    p.setLayout(new BoxLayout(p,BoxLayout.Y_AXIS));
    
    JPanel row;
    
    row = newPanel();
    row.add(new JLabel("Please enter your login info"));
    p.add(row);

    row = newPanel();
    row.setLayout(new GridLayout(2,2));

    row.add(new JLabel("Username"));
    row.add(usernameField = new JTextField(username==null?"":username,20));
    
    row.add(new JLabel("Password"));
    row.add(passwordField = new JPasswordField(password==null?"":password,20));

    p.add(row);
    
    row = newPanel();
    row.add(new JLabel("Remember"));
    check = new JCheckBox();
    if (!Util.isEmpty(username) || !Util.isEmpty(password)) check.setSelected(true);
    row.add(check);
    p.add(row);

   this.mainPanel = p;
  }
  
  public void show() {
    
    isCancelled = false;

    int res = JOptionPane.showConfirmDialog(null, mainPanel, "Login", 
                                            JOptionPane.OK_CANCEL_OPTION,
                                            JOptionPane.QUESTION_MESSAGE,
                                            null);
    isChecked = check.isSelected();
    if (res == JOptionPane.OK_OPTION) {
      username = usernameField.getText().trim();
      password = passwordField.getText().trim();
    } else {
      isCancelled = true;
    }
  }
  
  public boolean isReady() {
    return !Util.isEmpty(getUsername()) && !Util.isEmpty(getPassword());
  }
  
}